package com.example.hxds.dr.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.example.hxds.common.dto.RegisterNewDriverDTO;
import com.example.hxds.common.exception.HxdsException;
import com.example.hxds.common.util.ErrorCode;
import com.example.hxds.common.util.MathConstant;
import com.example.hxds.common.util.MessageConstant;
import com.example.hxds.dr.db.dao.DriverDao;
import com.example.hxds.dr.db.dao.DriverSettingsDao;
import com.example.hxds.dr.db.dao.WalletDao;
import com.example.hxds.dr.db.pojo.DriverSettingsEntity;
import com.example.hxds.dr.db.pojo.WalletEntity;
import com.example.hxds.dr.service.DriverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
@Service
public class DriverServiceImpl implements DriverService {

    @Autowired
    private DriverDao driverDao;
    @Autowired
    private WalletDao walletDao;
    @Autowired
    private DriverSettingsDao driverSettingsDao;

    @Transactional
    @LcnTransaction
    @Override
    public String registerNewDriver(RegisterNewDriverDTO registerNewDriverDTO) {
        Map<String, String> map = new HashMap<>();
        map.put("openId",registerNewDriverDTO.getOpenId());
        map.put("nickname",registerNewDriverDTO.getNickname());
        map.put("photo",registerNewDriverDTO.getPhoto());

        // 判断当前司机是否重复注册
        if (driverDao.hasDriver(map) > MathConstant.ZERO){
            // 注意：这里存在一个坑
            // 抛出的自定义异常注意修改异常状态码，否则openfeign客户端的fallbackFactory工厂的create方法获取不到FeignException异常
            throw new HxdsException(MessageConstant.DRIVER_REPEAT_REGISTER, ErrorCode.FIVE_PRE);
        }
        // 注册司机
        driverDao.insertDriver(map);

        // 初始化新注册司机的配置信息 司机接单相关配置以及司机钱包账户配置
        String driverId = driverDao.selectDriverIdByOpenId(registerNewDriverDTO.getOpenId());
        WalletEntity walletEntity = new WalletEntity();
        walletEntity.setDriverId(Long.parseLong(driverId));
        walletEntity.setBalance(new BigDecimal("0"));
        walletEntity.setPassword(null);
        walletDao.insertWallet(walletEntity);

        DriverSettingsEntity driverSettingsEntity = new DriverSettingsEntity();
        driverSettingsEntity.setDriverId(Long.parseLong(driverId));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("autoAccept",false);
        driverSettingsEntity.setSettings(jsonObject.toJSONString());
        driverSettingsDao.insertDriverSettings(driverSettingsEntity);

        return driverId;
    }
}
